using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;


namespace BackyardBunnies
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class SpriteManager : DrawableGameComponent
    {
        SpriteBatch spriteBatch;
        UserControlledSprite player;
        List<Sprite> spriteList = new List<Sprite>();
        
        //Use for player and bunny flipping
        SpriteEffects spriteEffectD;
        
        //Bunny Spawn stuff
        int bunnySpawnMin = 200;
        int bunnySpawnMax = 800;
        int nextBunnySpawn = 0;


 
        public SpriteManager(Game game)
            : base(game)
        {
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            //Reset the Bunny Spawn Time
            ResetSpawnTime();

            base.Initialize();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {

            //Update the Player sprite
            player.Update(gameTime, Game.Window.ClientBounds);

            //Bunny & Player flip controls
            if ((GamePad.GetState(PlayerIndex.One).DPad.Left == ButtonState.Pressed) || (Keyboard.GetState().IsKeyDown(Keys.Left)) || (Keyboard.GetState().IsKeyDown(Keys.A)))
                spriteEffectD = SpriteEffects.FlipHorizontally;
            if ((GamePad.GetState(PlayerIndex.One).DPad.Right == ButtonState.Pressed) || (Keyboard.GetState().IsKeyDown(Keys.Right)) || (Keyboard.GetState().IsKeyDown(Keys.D)))
                spriteEffectD = SpriteEffects.None;
            if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X > 0)
                spriteEffectD = SpriteEffects.None;
            if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X < 0)
                spriteEffectD = SpriteEffects.FlipHorizontally;

            //Loop for collisions
            for (int i = 0; i < spriteList.Count; ++i)
            {
                Sprite s = spriteList[i];
                s.Update(gameTime, Game.Window.ClientBounds);

                if (s.collisionRect.Intersects(player.collisionRect))
                {
                     //Increment score based on score value
                     ((Game1)Game).AddScore(spriteList[i].scoreValue);
                        
                     //Remove the sprite if collision
                     spriteList.RemoveAt(i);
                     --i;

                 }

             }

             //Handles bunny spawn times
             nextBunnySpawn -= gameTime.ElapsedGameTime.Milliseconds;
             if (nextBunnySpawn < 0)
             {
                 SpawnEnemy();
                 ResetSpawnTime();
             }


            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.FrontToBack,
                SaveStateMode.None);


            //Draw the player
            player.Draw(gameTime, spriteBatch,spriteEffectD);

            //Draw all sprites
            foreach (Sprite s in spriteList)
                s.Draw(gameTime, spriteBatch,spriteEffectD);

            spriteBatch.End();

            base.Draw(gameTime);
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            
            //Player Sprite (user controlled)
            player = new UserControlledSprite(
                Game.Content.Load<Texture2D>(@"Images/sharkmanBW"),
                new Vector2 (300,300), new Point(90, 129), 15, new Point(2, 1),
                new Point(2, 1), new Vector2 (6,6), 350);



            base.LoadContent();
        }

        private void ResetSpawnTime()
        {
            //Randomly generate spawn time based on Min and Max
            nextBunnySpawn = ((Game1)Game).rnd.Next(
                bunnySpawnMin, bunnySpawnMax);
        }

        private void SpawnEnemy()
        {
            Vector2 position;

            //Used for White, Blue and Black bunnies
            int bunnyType;

            //Randomly set position
            position = new Vector2(((Game1)Game).rnd.Next(150,700), ((Game1)Game).rnd.Next(75,475));
            
            //Randomly set bunny type
            bunnyType = ((Game1)Game).rnd.Next(1,100);

            //70% Chance of White Bunny
            if (bunnyType <= 80)
            {
                spriteList.Add(new AutomatedSprite(
                    Game.Content.Load<Texture2D>(@"Images/bunnyHop"),
                    position, new Point(52, 46), 10, new Point(0, 0),
                    new Point(4, 1), Vector2.Zero, 120, 15));
            }

            //20% Chance of Blue Bunny
            else if ((bunnyType > 80) && (bunnyType <= 90))
            {
                spriteList.Add(new AutomatedSprite(
                    Game.Content.Load<Texture2D>(@"Images/blueBunny"),
                    position, new Point(77, 68), 10, new Point(0, 0),
                    new Point(4, 1), Vector2.Zero, 120, 35));
            }

            //10% Chance of Black Bunny
            else if (bunnyType > 90)
            {
                spriteList.Add(new AutomatedSprite(
                    Game.Content.Load<Texture2D>(@"Images/blackBunny"),
                    position, new Point(127, 112), 15, new Point(0, 0),
                    new Point(4, 1), Vector2.Zero, 120, -150));
            }
        }

    }
}